package com.qxsx.midi.activity.home;

import android.graphics.drawable.ColorDrawable;
import android.os.Bundle;
import android.os.Handler;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.PopupWindow;
import android.widget.TextView;

import com.qxsx.midi.R;
import com.qxsx.midi.activity.base.BaseActivity;
import com.qxsx.midi.adapter.CateAdapter;
import com.qxsx.midi.adapter.ExamListAdapter;
import com.qxsx.midi.config.AppContext;
import com.qxsx.midi.config.DataManager;
import com.qxsx.midi.model.Voice;
import com.qxsx.midi.utils.CustomProgress;
import com.qxsx.midi.utils.MyNet;
import com.qxsx.midi.utils.SPUtils;
import com.qxsx.midi.utils.callBackJsonArray;
import com.qxsx.midi.view.XListView;
import com.qxsx.midi.view.XListView.IXListViewListener;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.List;

/**
 * Created by Joney on 2015/9/6.
 * 考级曲
 */
public class ExamListActivity extends BaseActivity implements OnClickListener, IXListViewListener {
    private CustomProgress customProgress;
    private static int page = 1;//初始化页号为1
    private static String grade = ""; //初始化等级
    private static String major = ""; //初始化专业
    private static int LEFT_P;  //左边POP选中位置
    private static int RIGHT_P; //右边POP选中位置
    //开题适配器
    private ExamListAdapter adapter;
    //考题集合
    private List<Voice> lists;
    private XListView lv_exam;
    //等级，专业
    private TextView tv_major, tv_grade;
    private LinearLayout ll_major, ll_grade;
    private LinearLayout ll_menu;
    private TextView tv_major_arrow, tv_grade_arrow;

    private Handler mHandler;  //执行下拉、上拉线程
    //分类
    private ListView lv_cate;
    private CateAdapter cateAdapter;
    private View mPopupWindowView;
    private static PopupWindow mPopupWindow;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_exam_list);
        setTitle("考级音频");
        setNavBtn(R.mipmap.back, 0);
        findById();
        inItData();
        mHandler = new Handler();
    }

    private void findById() {
        lv_exam = (XListView) findViewById(R.id.lv_exam);
        lv_exam.setXListViewListener(this);

        tv_major = (TextView) findViewById(R.id.tv_major);
        tv_major.setOnClickListener(this);

        tv_grade = (TextView) findViewById(R.id.tv_grade);
        tv_grade.setOnClickListener(this);

        ll_major = (LinearLayout) findViewById(R.id.ll_major);
        ll_major.setOnClickListener(this);

        ll_grade = (LinearLayout) findViewById(R.id.ll_grade);
        ll_grade.setOnClickListener(this);

        ll_menu = (LinearLayout) findViewById(R.id.ll_menu);
        ll_menu.setOnClickListener(this);

        tv_grade_arrow = (TextView) findViewById(R.id.tv_grade_arrow);
        tv_major_arrow = (TextView) findViewById(R.id.tv_major_arrow);

        //初始化
        tv_major.setSelected(true);
        ll_major.setClickable(true);
        tv_major_arrow.setSelected(true);
        ll_grade.setClickable(false);
    }

    private void inItData() {

        LEFT_P = DataManager.getManage().getMajorList().size() - 1;
        RIGHT_P = DataManager.getManage().getGradeList().size() - 1;
        lists = new ArrayList<>();
        adapter = new ExamListAdapter(this, lists);
        lv_exam.setAdapter(adapter);
        lv_exam.setPullLoadEnable(true);
        lv_exam.setPullRefreshEnable(true);
        getDataList(page, "", (String) SPUtils.get(AppContext.getContext(), "apply_major_id",""));
        //默认数据
    }

    @Override
    protected void onResume() {
        super.onResume();
    }


    /**
     * 下拉刷新
     */
    @Override
    public void onRefresh() {
        mHandler.postDelayed(new Runnable() {
            @Override
            public void run() {
                LoadRefresh();
            }
        }, 2000);
    }

    /**
     * 上拉加载更多
     */
    @Override
    public void onLoadMore() {
        mHandler.postDelayed(new Runnable() {
            @Override
            public void run() {
                LoadMore();
            }
        }, 2000);
    }

    /**
     * 下拉刷新
     */
    private void LoadRefresh() {
        page = 1;
        JSONArray array = new JSONArray();
        JSONObject object = new JSONObject();

        try {
            object.put("major_id", major);
            object.put("grade_num", grade + "");
            object.put("nowpage", 1 + "");
            object.put("pagesize", 10 + "");
            array.put(object);
        } catch (JSONException e) {
            e.printStackTrace();
        }
        MyNet.doPostJsonArray("513", array, new callBackJsonArray() {
            @Override
            public void run(Object code, Object message, JSONArray array) {
                if ("200".equals(code.toString())) {
                    lv_exam.stopRefresh();
                    lv_exam.setRefreshTime("2015-1-11");
                    try {
                        lists = new ArrayList<Voice>();
                        for (int i = 0; i < array.length(); i++) {
                            JSONObject object = array.getJSONObject(i);
                            Voice voice = new Voice();
                            voice.set_id(object.getString("id"));
                            voice.set_desc(object.getString("song_brief"));
                            voice.set_name(object.getString("song_name"));
                            lists.add(voice);
                        }
                        adapter.RemoveAll();
                        adapter.AddData(lists);
                        lv_exam.stopRefresh();
                    } catch (JSONException e) {
                        e.printStackTrace();
                    }


                }
            }
        });
    }

    /**
     * 上拉加载更多
     */
    private void LoadMore() {
        page++;
        JSONArray array = new JSONArray();
        JSONObject object = new JSONObject();

        try {
            object.put("major_id", major);
            object.put("grade_num", grade + "");
            object.put("nowpage", page + "");
            object.put("pagesize", 10 + "");
            array.put(object);
        } catch (JSONException e) {
            e.printStackTrace();
        }
        MyNet.doPostJsonArray("513", array, new callBackJsonArray() {
            @Override
            public void run(Object code, Object message, JSONArray array) {
                if ("200".equals(code.toString())) {
                    lv_exam.stopLoadMore();
                    try {
                        lists = new ArrayList<Voice>();
                        for (int i = 0; i < array.length(); i++) {
                            JSONObject object = array.getJSONObject(i);
                            Voice voice = new Voice();
                            voice.set_id(object.getString("id"));
                            voice.set_desc(object.getString("song_brief"));
                            voice.set_name(object.getString("song_name"));
                            lists.add(voice);
                        }

                        adapter.AddData(lists);
                        lv_exam.stopLoadMore();
                    } catch (JSONException e) {
                        e.printStackTrace();
                    }
                }
            }
        });

    }

    /**
     * 获取列表
     *
     * @param page
     * @param grade
     * @param majorId
     */
    private void getDataList(int page, String grade, String majorId) {
        customProgress = CustomProgress.show(ExamListActivity.this,"请稍后....",true,null);

        JSONArray array = new JSONArray();
        JSONObject object = new JSONObject();

        try {
            object.put("major_id", majorId);
            object.put("grade_num", grade + "");
            object.put("nowpage", page + "");
            object.put("pagesize", 10 + "");
            array.put(object);
        } catch (JSONException e) {
            e.printStackTrace();
        }
        MyNet.doPostJsonArray("513", array, new callBackJsonArray() {
            @Override
            public void run(Object code, Object message, JSONArray array) {
                if ("200".equals(code.toString())) {
                    try {
                        lists = new ArrayList<Voice>();
                        for (int i = 0; i < array.length(); i++) {
                            JSONObject object = array.getJSONObject(i);
                            Voice voice = new Voice();
                            voice.set_id(object.getString("id"));
                            voice.set_desc(object.getString("song_brief"));
                            voice.set_name(object.getString("song_name"));
                            lists.add(voice);
                        }
                        adapter.RemoveAll();
                        adapter.AddData(lists);
                    } catch (JSONException e) {
                        e.printStackTrace();
                    }


                }
                customProgress.dismiss();
            }
        });
    }


    /**
     * @param component
     * @param v
     */
    @Override
    protected void HandleTitleBarEvent(TitleBar component, View v) {
        switch (component) {
            case LEFT:
                finish();
                break;
        }

    }

    /**
     * Called when a view has been clicked.
     *
     * @param v The view that was clicked.
     */
    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.tv_major:
                // 获取自定义布局文件视图
                mPopupWindowView = LayoutInflater.from(ExamListActivity.this).inflate(R.layout.major_pop_item, null, false);
                lv_cate = (ListView) mPopupWindowView.findViewById(R.id.lv_cate);
                // 创建PopupWindow实例,LayoutParams.MATCH_PARENT分别是宽度和高度
                mPopupWindow = new PopupWindow(mPopupWindowView, ViewGroup.LayoutParams.FILL_PARENT, ViewGroup.LayoutParams.FILL_PARENT, true);
                ColorDrawable dw = new ColorDrawable(ExamListActivity.this.getApplicationContext().getResources().getColor(R.color.theme_transparency));
                mPopupWindow.setBackgroundDrawable(dw);
                // 这里是位置显示方式,在屏幕的右侧,v(标题栏)之下
                mPopupWindowView.setFocusable(true);
                mPopupWindowView.setFocusableInTouchMode(true);
                mPopupWindow.setBackgroundDrawable(ExamListActivity.this.getResources().getDrawable(R.mipmap.study_call_menu_bg));
                mPopupWindowView.setOnClickListener(new OnClickListener() {

                    @Override
                    public void onClick(View v) {
                        if (mPopupWindow.isShowing()) {
                            mPopupWindow.dismiss();
                        }
                    }
                });
                mPopupWindowView.setOnKeyListener(new View.OnKeyListener() {
                    @Override
                    public boolean onKey(View arg0, int arg1, KeyEvent arg2) {
                        if (arg1 == KeyEvent.KEYCODE_BACK) {
                            if (mPopupWindow != null) {
                                mPopupWindow.dismiss();
                            }
                        }
                        return false;
                    }
                });
                cateAdapter = new CateAdapter(ExamListActivity.this, DataManager.getManage().getMajorList(), "LEFT");
                lv_cate.setAdapter(cateAdapter);
                cateAdapter.setChoose(LEFT_P);
                lv_cate.setOnItemClickListener(new AdapterView.OnItemClickListener() {
                    @Override
                    public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                        cateAdapter.setChoose(position);
                        tv_major.setText(DataManager.getManage().getMajorList().get(position).getMajor_name());
                        LEFT_P = position;
                        if (mPopupWindow != null) {
                            major = DataManager.getManage().getMajorList().get(position).getMajor_id();
                            getDataList(page, grade, major);

                        }
                        mPopupWindow.dismiss();
                    }
                });
                mPopupWindow.showAsDropDown(v, 0, 5);
                mPopupWindow.setFocusable(true);
                mPopupWindow.setOutsideTouchable(true);
                tv_major.setSelected(true);
                tv_grade.setSelected(false);
                ll_major.setClickable(true);
                tv_major_arrow.setSelected(true);
                tv_grade_arrow.setSelected(false);
                ll_grade.setClickable(false);
                break;
            case R.id.tv_grade:

                // 获取自定义布局文件视图
                mPopupWindowView = LayoutInflater.from(ExamListActivity.this).inflate(R.layout.major_pop_item, null, false);
                lv_cate = (ListView) mPopupWindowView.findViewById(R.id.lv_cate);
                // 创建PopupWindow实例,LayoutParams.MATCH_PARENT分别是宽度和高度
                mPopupWindow = new PopupWindow(mPopupWindowView, ViewGroup.LayoutParams.FILL_PARENT, ViewGroup.LayoutParams.FILL_PARENT, true);
                ColorDrawable dw2 = new ColorDrawable(ExamListActivity.this.getApplicationContext().getResources().getColor(R.color.theme_transparency));
                mPopupWindow.setBackgroundDrawable(dw2);
                // 这里是位置显示方式,在屏幕的右侧,v(标题栏)之下
                mPopupWindowView.setFocusable(true);
                mPopupWindowView.setFocusableInTouchMode(true);
                mPopupWindow.setBackgroundDrawable(ExamListActivity.this.getResources().getDrawable(R.mipmap.study_call_menu_bg));
                mPopupWindowView.setOnClickListener(new OnClickListener() {

                    @Override
                    public void onClick(View v) {
                        if (mPopupWindow.isShowing()) {
                            mPopupWindow.dismiss();
                        }
                    }
                });
                mPopupWindowView.setOnKeyListener(new View.OnKeyListener() {
                    @Override
                    public boolean onKey(View arg0, int arg1, KeyEvent arg2) {
                        if (arg1 == KeyEvent.KEYCODE_BACK) {
                            if (mPopupWindow != null) {
                                mPopupWindow.dismiss();
                            }
                        }
                        return false;
                    }
                });
                mPopupWindow.showAsDropDown(v, 0, 5);
                mPopupWindow.setFocusable(true);
                mPopupWindow.setOutsideTouchable(true);
                cateAdapter = new CateAdapter(ExamListActivity.this, DataManager.getManage().getGradeList(), "RIGHT");
                lv_cate.setAdapter(cateAdapter);
                cateAdapter.setChoose(RIGHT_P);
                lv_cate.setOnItemClickListener(new AdapterView.OnItemClickListener() {
                    @Override
                    public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                        cateAdapter.setChoose(position);
                        tv_grade.setText(DataManager.getManage().getGradeList().get(position).getMajor_name());
                        RIGHT_P = position;
                        if (mPopupWindow != null) {
                            grade = DataManager.getManage().getGradeList().get(position).getMajor_id();
                            getDataList(page, grade, major);
                        }
                        mPopupWindow.dismiss();
                    }
                });
                tv_major.setSelected(false);
                tv_grade.setSelected(true);
                ll_major.setClickable(false);
                tv_major_arrow.setSelected(false);
                tv_grade_arrow.setSelected(true);
                ll_grade.setClickable(true);
                break;
            case R.id.ll_major:

                break;
            case R.id.ll_grade:

                break;
        }
    }
}
